/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-03-08     Hao       the first version
 */
#include "driver.h"
#include "foc_utils.h"
#include "default.h"

// 用户接口
#include <hardware/gpio_operate.h>
#include <hardware/pwm_operate.h>

Driver::Driver()
{
    voltage_power_supply_ = DEF_POWER_SUPPLY;
    voltage_limit_ = NOT_SET;
}

Driver::~Driver()
{
}

// enable motor driver
void Driver::enable()
{
    // 使能引脚控制，高电平使能，低电平失能
    gpio_write(&enable_pin, 1);

    // set zero to PWM
    setPwm(0, 0, 0);
}

// disable motor driver
void Driver::disable()
{
    // set zero to PWM
    setPwm(0, 0, 0);

    // 使能引脚控制，高电平使能，低电平失能
    gpio_write(&enable_pin, 0);
}

// init hardware pins
void Driver::init()
{
    // sanity check for the voltage limit configuration
    if (!_isset(voltage_limit_) || voltage_limit_ > voltage_power_supply_)
        voltage_limit_ = voltage_power_supply_;

    enable();
}

// 设置项电压
void Driver::setPwm(float Ua, float Ub, float Uc)
{
    // limit the voltage in driver
    Ua = _constrain(Ua, 0.0f, voltage_limit_);
    Ub = _constrain(Ub, 0.0f, voltage_limit_);
    Uc = _constrain(Uc, 0.0f, voltage_limit_);
    // 计算占空比
    // limited in [0,1]
    duty_a_ = _constrain(Ua / voltage_power_supply_, 0.0f, 1.0f);
    duty_b_ = _constrain(Ub / voltage_power_supply_, 0.0f, 1.0f);
    duty_c_ = _constrain(Uc / voltage_power_supply_, 0.0f, 1.0f);

    // hardware specific writing
    // hardware specific function - depending on driver and mcu
    set_hardware_pwm(duty_a_, duty_b_, duty_c_);
}

// 硬件设置pwm接口，这里A相就是通道1，B相就是通道2，C相就是通道3
void Driver::set_hardware_pwm(float duty_cycle_a, float duty_cycle_b, float duty_cycle_c)
{
    motor_pwm_set(1, duty_cycle_a);
    motor_pwm_set(2, duty_cycle_b);
    motor_pwm_set(3, duty_cycle_c);
}
